const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 确保上传目录存在
const ensureUploadDir = (dir) => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
};

// 配置存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    let uploadPath = 'uploads/';
    
    // 根据文件字段名分配存储目录
    if (file.fieldname === 'productImages') {
      uploadPath = 'uploads/products/';
    } else if (file.fieldname === 'categoryImage') {
      uploadPath = 'uploads/categories/';
    } else if (file.fieldname === 'avatar') {
      uploadPath = 'uploads/avatars/';
    }

    ensureUploadDir(uploadPath);
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname).toLowerCase();
    cb(null, `${file.fieldname}-${uniqueSuffix}${ext}`);
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 只允许图片文件
  const allowedMimeTypes = [
    'image/jpeg', 
    'image/png', 
    'image/gif', 
    'image/webp'
  ];

  if (allowedMimeTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('只允许上传图片文件 (JPG, PNG, GIF, WEBP)'), false);
  }
};

// 配置multer
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: parseInt(process.env.MAX_FILE_SIZE) || 5 * 1024 * 1024, // 5MB
    files: 10 // 最多10个文件
  }
});

// 上传错误处理中间件
exports.handleUploadError = (err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    if (err.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({
        success: false,
        message: `文件大小超出限制 (最大 ${(process.env.MAX_FILE_SIZE / 1024 / 1024).toFixed(1)}MB)`
      });
    }
    if (err.code === 'LIMIT_FILE_COUNT') {
      return res.status(400).json({
        success: false,
        message: '文件数量超出限制 (最多10个文件)'
      });
    }
    return res.status(400).json({
      success: false,
      message: `上传错误: ${err.message}`
    });
  } else if (err.message === '只允许上传图片文件 (JPG, PNG, GIF, WEBP)') {
    return res.status(400).json({
      success: false,
      message: err.message
    });
  }
  next(err);
};

// 导出不同场景的上传配置
exports.uploadProductImages = upload.array('productImages', 5); // 商品图片(最多5张)
exports.uploadCategoryImage = upload.single('categoryImage');   // 分类图片(单张)
exports.uploadAvatar = upload.single('avatar');                 // 用户头像(单张)